import config from '@/config'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import { toBase64 } from '@/utils/common'
import {
	login,
	logout,
	getInfo,
	loadRefreshToken,
	getUserInfoByCode,
	getPermissions
} from '@/api/login'

import {
	fileDownLoad
} from '@/api/system/common'

import {
	getToken,
	setToken,
	removeToken,
	setRefreshToken,
	getRefreshToken,
	removeRefreshToken
} from '@/utils/auth'

const baseUrl = config.baseUrl

const user = {
	state: {
		token: getToken(),
		name: storage.get(constant.name),
		avatar: storage.get(constant.avatar),
		roles: storage.get(constant.roles),
		permissions: storage.get(constant.permissions) || [],
		allPermissions:storage.get(constant.allPermissions) || [],
		refreshToken: '',
		dept: {},
		userInfo: storage.get(constant.userInfo),
		loginNum:0
	},
	mutations: {
		SET_TOKEN: (state, token) => {
			setToken(token)
			state.token = token
		},
		SET_REFRESH_TOKEN: (state, refreshToken) => {
			state.refreshToken = refreshToken
			setRefreshToken(refreshToken)
		},
		SET_NAME: (state, name) => {
			state.name = name
			console.log(state.name)
			storage.set(constant.name, name)
		},
		SET_AVATAR: (state, avatar) => {
			state.avatar = avatar
			storage.set(constant.avatar, avatar)
		},
		SET_DEPT: (state, dept) => {
			state.dept = dept
			storage.set(constant.dept, dept)
		},
		SET_INFO: (state, userInfo) => {
			state.userInfo = userInfo
			storage.set(constant.userInfo, userInfo)
		},
		SET_ROLES: (state, roles) => {
			state.roles = roles
			storage.set(constant.roles, roles)
		},
		SET_PERMISSIONS: (state, permissions) => {
			state.permissions = permissions
			storage.set(constant.permissions, permissions)
		},
		SET_ALL_PERMISSIONS(state, permissions){
			state.allPermissions = permissions
			storage.set(constant.allPermissions, permissions)
		},
		SET_AUTH_CODE:(state, code) =>{
			state.authCode = code
			storage.set(constant.authCode, code)
		},
		SET_LOGIN_NUM:(state) =>{
			state.loginNum++
		},
		CLEAR_LOGIN_NUM:(state) =>{
			state.loginNum = 0
		}
	},
	actions: {
		// 登录
		Login({
			commit,
			dispatch
		}, userInfo) {
			// const username = userInfo.username.trim()
			// const password = userInfo.password
			// const code = userInfo.code
			// const uuid = userInfo.uuid
			return new Promise((resolve, reject) => {
				login(userInfo).then(res => {
					const user = res.data.result.user
					commit('SET_TOKEN', res.data.result.token)
					commit('SET_REFRESH_TOKEN', res.data.result.refreshToken)
					// commit('SET_AVATAR', user.avatar)
					commit('SET_NAME', user.nickname)
					commit('SET_INFO', user)
					commit('SET_DEPT', user.dept)
					dispatch('GetAvatarUrl',user.avatar)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
		RefreshToken({
			commit,
			state
		}) { // 刷新token
			return new Promise((resolve, reject) => {
				loadRefreshToken({
					refreshToken: state.refreshToken,
					token: getToken()
				}).then(res => {
					if (res.data.success) {
						commit('SET_TOKEN', res.data.result.token)
						commit('SET_REFRESH_TOKEN', res.data.result.refreshToken)
					}
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 获取用户信息
		GetInfo({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				getInfo().then(res => {
					const user = res.user
					const avatar = (user == null || user.avatar == "" || user.avatar == null) ? require(
						"@/static/images/profile.jpg") : baseUrl + user.avatar
					const username = (user == null || user.userName == "" || user.userName == null) ? "" : user.userName
					if (res.roles && res.roles.length > 0) {
						commit('SET_ROLES', res.roles)
						commit('SET_PERMISSIONS', res.permissions)
					} else {
						commit('SET_ROLES', ['ROLE_DEFAULT'])
					}
					commit('SET_NAME', username)
					commit('SET_AVATAR', avatar)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
		LogOut({ commit,state }) {// 退出系统
			return new Promise((resolve, reject) => {
				logout({username:state.userInfo.username}).then(() => {
					commit('SET_TOKEN', '')
					commit('SET_REFRESH_TOKEN', '')
					commit('SET_ROLES', [])
					commit('SET_PERMISSIONS', [])
					commit('SET_ALL_PERMISSIONS', [])
					removeToken()
					removeRefreshToken()
					storage.clean()
					commit('CLEAR_LOGIN_NUM')
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},
	  LoginSSO({ commit,dispatch },data) {
			return new Promise((resolve, reject) => {
				login(data).then(res => {
					const user = res.data.result.user
					// commit('SET_AUTH_CODE',code)
					commit('SET_TOKEN', res.data.result.token)
					commit('SET_REFRESH_TOKEN', res.data.result.refreshToken)
					// commit('SET_AVATAR', user.avatar)
					dispatch('GetAvatarUrl',user.avatar)
					commit('SET_NAME', user.nickname)
					commit('SET_INFO', user)
					commit('SET_DEPT', user.dept)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
		GetAvatarUrl({ commit },fileNo){//获取头像url
			return new Promise(async(resolve, reject) => {
				const file = await fileDownLoad(fileNo)
				const url =  'data:image/png;base64,'+uni.arrayBufferToBase64(file.data);
				commit('SET_AVATAR', url)
			})
		},
		GetAuth({ commit }) {//获取权限
			return new Promise((resolve, reject) => {
				getPermissions().then(res => {
					const data = res.data
					if (data.success) {
						const permissions = []
						data.result.datas.forEach(item => {
							permissions.push(item.elementId)
						})
						commit('SET_PERMISSIONS', permissions)
						const allPermissions = []
						data.result.allDatas.forEach(item => {
							allPermissions.push(item.elementId)
						})
						commit('SET_ALL_PERMISSIONS', allPermissions)
					}
					resolve(res)
				})
			})
		}
	}
}

export default user